package com.thz.system.service.record.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thz.common.dto.ConversionRecordDTO;
import com.thz.common.entity.ConversionRecord;
import com.thz.common.enums.ConversionStatus;
import com.thz.common.enums.ConversionType;
import com.thz.common.utils.FileUtils;
import com.thz.common.entity.ConversionRecordVideoToGif;
import com.thz.system.mapper.gif.ConversionVideoToGifMapper;
import com.thz.system.mapper.record.ConversionRecordMapper;
import com.thz.system.service.record.IConversionRecordService;
import com.thz.system.utils.cos.CosFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统一转换记录服务实现类
 * 
 * @author THZ
 * @date 2025
 */
@Slf4j
@Service
public class ConversionRecordServiceImpl implements IConversionRecordService {
    
    @Autowired
    private ConversionRecordMapper conversionRecordMapper;
    
    @Autowired
    private ConversionVideoToGifMapper conversionVideoToGifMapper;
    
    @Autowired
    private CosFileUtils cosFileUtils;
    
    @Value("${app.domain:http://localhost:9091}")
    private String serverDomain;
    
    @Override
    public ConversionRecord createRecord(ConversionRecord record) {
        conversionRecordMapper.insert(record);
        return record;
    }
    
    @Override
    public void updateRecord(ConversionRecord record) {
        conversionRecordMapper.updateById(record);
    }
    
    @Override
    public List<ConversionRecordDTO> getUserConversionHistory(Long userId, int limit) {
        LambdaQueryWrapper<ConversionRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConversionRecord::getUserId, userId)
                .orderByDesc(ConversionRecord::getCreateTime)
                .last("LIMIT " + limit);
        
        List<ConversionRecord> records = conversionRecordMapper.selectList(queryWrapper);
        return records.stream()
                .map(this::buildDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<ConversionRecordDTO> getConversionHistoryByIp(String ipAddress, int limit) {
        LambdaQueryWrapper<ConversionRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConversionRecord::getIpAddress, ipAddress)
                .orderByDesc(ConversionRecord::getCreateTime)
                .last("LIMIT " + limit);
        
        List<ConversionRecord> records = conversionRecordMapper.selectList(queryWrapper);
        return records.stream()
                .map(this::buildDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public void deleteRecord(Long id) {
        conversionRecordMapper.deleteById(id);
    }
    
    @Override
    public ConversionRecord findByReferenceId(Long referenceId, String conversionType) {
        LambdaQueryWrapper<ConversionRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConversionRecord::getReferenceId, referenceId)
                .eq(ConversionRecord::getConversionType, conversionType)
                .last("LIMIT 1");
        return conversionRecordMapper.selectOne(queryWrapper);
    }
    
    /**
     * 构建DTO，包含详细信息和URL
     */
    private ConversionRecordDTO buildDTO(ConversionRecord record) {
        ConversionRecordDTO dto = new ConversionRecordDTO();
        BeanUtil.copyProperties(record, dto);
        
        // 设置转换类型描述
        try {
            ConversionType type = ConversionType.fromCode(record.getConversionType());
            dto.setConversionTypeDescription(type.getDescription());
        } catch (Exception e) {
            dto.setConversionTypeDescription(record.getConversionType());
        }
        
        // 设置转换状态描述
        try {
            ConversionStatus status = ConversionStatus.fromCode(record.getConversionStatus());
            dto.setConversionStatusDescription(status.getDescription());
        } catch (Exception e) {
            dto.setConversionStatusDescription("未知");
        }
        
        // 格式化文件大小
        if (record.getOriginalFileSize() != null) {
            dto.setOriginalFileSizeFormatted(FileUtils.formatFileSize(record.getOriginalFileSize()));
        }
        if (record.getOutputFileSize() != null) {
            dto.setOutputFileSizeFormatted(FileUtils.formatFileSize(record.getOutputFileSize()));
            
            // 计算压缩率
            if (record.getOriginalFileSize() != null && record.getOriginalFileSize() > 0) {
                double ratio = (1.0 - (double) record.getOutputFileSize() / record.getOriginalFileSize()) * 100;
                dto.setCompressionRatio(Math.max(0, ratio));
            }
        }
        
        // 构建输出文件URL（自动处理COS URL和本地路径）
        if (record.getOutputFilename() != null) {
            String outputUrl = record.getOutputFilename();
            
            // 【修复】如果outputFilename是临时路径（temp://开头），尝试从子表获取正确的COS URL
            if (outputUrl.startsWith("temp://")) {
                log.warn("检测到临时路径，尝试从子表获取COS URL - 记录ID: {}, 类型: {}, 临时路径: {}", 
                        record.getId(), record.getConversionType(), outputUrl);
                
                // 尝试从子表获取正确的COS URL
                if (ConversionType.VIDEO_TO_GIF.getCode().equals(record.getConversionType()) && record.getReferenceId() != null) {
                    try {
                        ConversionRecordVideoToGif subRecord = conversionVideoToGifMapper.selectById(record.getReferenceId());
                        if (subRecord != null && subRecord.getGifFilePath() != null 
                                && !subRecord.getGifFilePath().startsWith("temp://")) {
                            // 找到了正确的COS URL，更新统一记录表
                            String cosUrl = subRecord.getGifFilePath();
                            log.info("从子表获取到COS URL - 记录ID: {}, COS URL: {}", record.getId(), cosUrl);
                            
                            // 更新统一记录表
                            record.setOutputFilename(cosUrl);
                            record.setUpdateTime(java.time.LocalDateTime.now());
                            conversionRecordMapper.updateById(record);
                            log.info("统一记录表已更新 - 记录ID: {}, COS URL: {}", record.getId(), cosUrl);
                            
                            outputUrl = cosUrl;
                        } else {
                            // 子表中也是临时路径，使用本地文件代理
                            String localPath = outputUrl.substring(7);  // 移除 "temp://" 前缀
                            outputUrl = serverDomain + "/api/files/local?path=" + URLEncoder.encode(localPath, StandardCharsets.UTF_8);
                            log.warn("子表中也是临时路径，使用本地文件代理 - 记录ID: {}, 本地路径: {}", record.getId(), localPath);
                        }
                    } catch (Exception e) {
                        log.error("从子表获取COS URL失败 - 记录ID: {}, 类型: {}", record.getId(), record.getConversionType(), e);
                        // 使用本地文件代理
                        String localPath = outputUrl.substring(7);  // 移除 "temp://" 前缀
                        outputUrl = serverDomain + "/api/files/local?path=" + URLEncoder.encode(localPath, StandardCharsets.UTF_8);
                    }
                } else {
                    // 其他类型或没有referenceId，使用本地文件代理
                    String localPath = outputUrl.substring(7);  // 移除 "temp://" 前缀
                    outputUrl = serverDomain + "/api/files/local?path=" + URLEncoder.encode(localPath, StandardCharsets.UTF_8);
                }
            }
            
            // 如果不是完整的URL，则需要构建URL
            if (!outputUrl.startsWith("http://") && !outputUrl.startsWith("https://") && !outputUrl.startsWith(serverDomain)) {
                // 根据转换类型构建不同的路径前缀
                String pathPrefix;
                if (ConversionType.FILE_TO_SVG.getCode().equals(record.getConversionType())) {
                    pathPrefix = serverDomain + "/api/files/svg/";
                } else {
                    pathPrefix = serverDomain + "/api/files/";
                }
                // 使用CosFileUtils自动处理本地文件名
                outputUrl = cosFileUtils.getFileUrl(outputUrl, pathPrefix);
            }
            
            // 对于COS URL，使用代理URL用于预览（避免CORS和Content-Disposition问题）
            // 对于下载，直接使用COS URL（下载不需要预览）
            if (outputUrl.startsWith("http://") || outputUrl.startsWith("https://")) {
                // 如果是本地文件代理URL，直接使用
                if (outputUrl.startsWith(serverDomain + "/api/files/local")) {
                    dto.setOutputUrl(outputUrl);
                    dto.setDownloadUrl(outputUrl + "&download=true");
                } else {
                    // COS URL，转换为代理URL用于预览
                    String proxyUrl = serverDomain + "/api/files/proxy?url=" + 
                        URLEncoder.encode(outputUrl, StandardCharsets.UTF_8);
                    dto.setOutputUrl(proxyUrl);
                    // 下载URL也使用代理URL（添加download=true参数，避免CORS问题）
                    dto.setDownloadUrl(proxyUrl + "&download=true");
                }
            } else {
                // 本地文件
                dto.setOutputUrl(outputUrl);
                dto.setDownloadUrl(outputUrl + "?download=true");
            }
        }
        
        // 构建缩略图URL（自动处理COS URL和本地路径）
        if (record.getThumbnailFilename() != null) {
            String thumbnailUrl = record.getThumbnailFilename();
            
            // 如果不是完整的URL，则需要构建URL
            if (!thumbnailUrl.startsWith("http://") && !thumbnailUrl.startsWith("https://")) {
                // 使用CosFileUtils自动处理本地文件名
                thumbnailUrl = cosFileUtils.getFileUrl(
                    thumbnailUrl, 
                    serverDomain + "/api/files/"
                );
            }
            
            // 对于COS URL，使用代理URL用于预览
            if (thumbnailUrl.startsWith("http://") || thumbnailUrl.startsWith("https://")) {
                // COS URL，转换为代理URL
                thumbnailUrl = serverDomain + "/api/files/proxy?url=" + 
                    java.net.URLEncoder.encode(thumbnailUrl, java.nio.charset.StandardCharsets.UTF_8);
            }
            
            dto.setThumbnailUrl(thumbnailUrl);
            log.debug("构建缩略图URL - 类型: {}, URL: {}", record.getConversionType(), thumbnailUrl);
        }
        
        return dto;
    }
}

